<template>
  <div class="employee-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">员工列表</span>
          <el-button type="primary" @click="handleAdd" class="add-btn">
            <el-icon><Plus /></el-icon>新增员工
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="员工姓名">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入员工姓名" 
              class="search-input"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="部门">
            <el-select 
              v-model="searchForm.department" 
              placeholder="请选择部门" 
              class="search-select"
              clearable
            >
              <el-option
                v-for="dept in departmentList"
                :key="dept.id"
                :label="dept.name"
                :value="dept.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetSearch" class="reset-btn">
              <el-icon><RefreshRight /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        class="employee-table"
        :header-cell-style="{
          background: '#f8faff',
          color: '#303133',
          fontWeight: '600',
          fontSize: '14px',
        }"
      >
        <el-table-column prop="employeeNo" label="工号" width="100" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="department.name" label="部门" width="120" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="phoneNumber" label="联系电话" width="150" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)" class="action-btn">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button link type="primary" @click="handleView(scope.row)" class="action-btn">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)" class="action-btn">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>

      <!-- 员工信息对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增员工' : dialogType === 'edit' ? '编辑员工' : '员工详情'"
        width="600px"
        class="employee-dialog"
        :append-to-body="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        top="5vh"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          :disabled="dialogType === 'view'"
        >
          <el-form-item label="工号" prop="employeeNo">
            <el-input v-model="form.employeeNo" :disabled="dialogType === 'edit'" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio v-for="option in genderOptions" :key="option.value" :label="option.value">
                {{ option.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="部门" prop="departmentId">
            <el-select v-model="form.departmentId" placeholder="请选择部门">
              <el-option
                v-for="dept in departmentList"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="职位" prop="position">
            <el-input v-model="form.position" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phoneNumber">
            <el-input v-model="form.phoneNumber" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="入职日期" prop="hireDate">
            <el-date-picker
              v-model="form.hireDate"
              type="date"
              placeholder="选择入职日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status">
              <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
            <el-input v-model="form.password" type="password" />
          </el-form-item>
          <el-form-item label="管理员" prop="isAdmin">
            <el-switch v-model="form.isAdmin" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">
              <el-icon><Close /></el-icon>取消
            </el-button>
            <el-button
              type="primary"
              @click="handleSubmit"
              v-if="dialogType !== 'view'"
              class="submit-btn"
            >
              <el-icon><Check /></el-icon>确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {
  Plus,
  Edit,
  View,
  Delete,
  Search,
  RefreshRight,
  Check,
  Close,
} from '@element-plus/icons-vue'
import { getEmployeeList, addEmployee, editEmployee, deleteEmployee } from '@/api/admin/List'
import DepartmentApi from '@/api/admin/Department'

// 搜索表单
const searchForm = reactive({
  name: '',
  department: ''
})

// 表格数据
const tableData = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  employeeNo: '',
  name: '',
  gender: 0,
  phoneNumber: '',
  email: '',
  departmentId: '',
  position: '',
  hireDate: '',
  status: 1,
  isAdmin: false,
  password: '',
})

// 表单校验规则
const rules = {
  employeeNo: [{ required: true, message: '请输入工号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  departmentId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  phoneNumber: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  hireDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
}

// 性别选项
const genderOptions = [
  { label: '女', value: 0 },
  { label: '男', value: 1 },
]

// 状态选项
const statusOptions = [
  { label: '在职', value: 1 },
  { label: '离职', value: 0 },
]

// 部门列表
const departmentList = ref([])

// 获取部门列表
const getDepartmentList = async () => {
  try {
    const res = await DepartmentApi.getDepartmentList()
    if (res.data) {
      departmentList.value = res.data.records || []
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 获取员工列表数据
const getList = async () => {
  try {
    console.log('搜索参数:', searchForm) // 添加日志
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      name: searchForm.name || '',
      department: searchForm.department || ''
    }
    const res = await getEmployeeList(params)
    if (res.data) {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.department = ''
  currentPage.value = 1
  getList()
}

// 新增员工
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach((key) => {
    if (key === 'department') return
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 查看员工
const handleView = (row) => {
  dialogType.value = 'view'
  Object.keys(form).forEach((key) => {
    if (key === 'department') return
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除员工 "${row.name}" 的信息吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await deleteEmployee(row.id)
      if (res.data) {
        ElMessage.success(`已成功删除员工 "${row.name}" 的信息`)
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }).catch(() => {
    // 用户取消删除操作
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: dialogType.value === 'add' ? '正在添加...' : '正在修改...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        const apiMethod = dialogType.value === 'add' ? addEmployee : editEmployee
        const submitData = {
          ...form,
          adminNo: localStorage.getItem('adminNo') || '',
          departmentId: form.departmentId
        }
        // 如果是编辑，需要传入id
        if (dialogType.value === 'edit') {
          submitData.id = form.id
        }
        const res = await apiMethod(submitData)
        if (res.data) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
          dialogVisible.value = false
          getList()
        } else {
          ElMessage.error(res.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.message || '操作失败')
      } finally {
        loading.close()
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  Object.keys(form).forEach((key) => {
    form[key] = key === 'gender' ? 0 
              : key === 'status' ? 1 
              : key === 'isAdmin' ? false 
              : key === 'departmentId' ? '' 
              : ''
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getList() // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList() // 重新加载数据
}

// 页面加载时获取数据
onMounted(() => {
  getList()
  getDepartmentList()
})
</script>

<style scoped lang="scss">
.employee-list {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .list-card {
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    overflow: hidden;

    &:hover {
      box-shadow: 0 12px 32px rgba(24, 144, 255, 0.1);
      transform: translateY(-2px);
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;

    .header-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      position: relative;
      padding-left: 12px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: #1890ff;
        border-radius: 2px;
      }
    }

    .add-btn {
      background: linear-gradient(135deg, #1890ff, #36a6ff);
      border: none;
      border-radius: 20px;
      padding: 8px 16px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);

      .el-icon {
        margin-right: 4px;
      }

      &:hover {
        background: linear-gradient(135deg, #40a9ff, #5cbbff);
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
        transform: translateY(-2px);
      }

      &:active {
        background: linear-gradient(135deg, #096dd9, #1890ff);
        transform: translateY(0);
      }
    }
  }

  .search-area {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f8faff;
    border-radius: 8px;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
    }

    .search-input,
    .search-select {
      width: 220px;

      :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;

        &:hover,
        &.is-focus {
          box-shadow: 0 0 0 1px #1890ff inset;
        }
      }
    }

    .search-btn {
      background: linear-gradient(135deg, #1890ff, #36a6ff);
      border: none;
      border-radius: 20px;
      padding: 8px 16px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);
      margin-right: 10px;

      .el-icon {
        margin-right: 4px;
      }

      &:hover {
        background: linear-gradient(135deg, #40a9ff, #5cbbff);
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
        transform: translateY(-2px);
      }

      &:active {
        background: linear-gradient(135deg, #096dd9, #1890ff);
        transform: translateY(0);
      }
    }

    .reset-btn {
      background: #f5f7fa;
      color: #606266;
      border: none;
      border-radius: 20px;
      padding: 8px 16px;
      transition: all 0.3s ease;

      .el-icon {
        margin-right: 4px;
      }

      &:hover {
        background: #e6f7ff;
        color: #1890ff;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        transform: translateY(-2px);
      }

      &:active {
        background: #dcf0fd;
        transform: translateY(0);
      }
    }
  }

  .employee-table {
    margin: 16px 0;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    :deep(.el-table__row) {
      transition: all 0.3s;

      &:hover {
        background-color: #f8faff !important;
      }
    }

    :deep(.el-table__cell) {
      padding: 10px 0;
    }

    :deep(.el-tag) {
      padding: 0 10px;
      height: 28px;
      line-height: 28px;
      border-radius: 4px;
      font-weight: 500;
      font-size: 12px;

      &.el-tag--success {
        background-color: rgba(82, 196, 26, 0.08);
        border-color: rgba(82, 196, 26, 0.2);
        color: #52c41a;
      }

      &.el-tag--info {
        background-color: rgba(144, 147, 153, 0.08);
        border-color: rgba(144, 147, 153, 0.2);
        color: #909399;
      }
    }

    .action-btn {
      font-size: 13px;
      font-weight: 500;
      transition: all 0.3s;
      margin: 0 4px;

      .el-icon {
        margin-right: 2px;
      }

      &:hover {
        transform: translateY(-2px);
        opacity: 0.8;
      }

      &:active {
        color: #096dd9;
      }

      &.el-button--danger:hover {
        opacity: 0.8;
        transform: translateY(-2px);
      }

      &.el-button--danger:active {
        color: #cf1322;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;

    :deep(.custom-pagination) {
      padding: 0;

      .el-pagination__total {
        margin-right: 16px;
        color: #606266;
        font-weight: 500;
      }

      .el-pagination__sizes {
        margin-right: 16px;

        .el-select .el-input {
          width: 110px;

          .el-input__wrapper {
            background-color: #f5f7fa;
            border-radius: 20px;
          }
        }
      }

      button {
        background-color: #f5f7fa;
        border-radius: 4px;
        margin: 0 3px;
        color: #606266;
        transition: all 0.2s ease;

        &:hover {
          color: #1890ff;
          background-color: #e6f7ff;
        }

        &:disabled {
          color: #c0c4cc;
        }
      }

      .btn-prev,
      .btn-next {
        padding: 0 8px;

        &:hover {
          background-color: #e6f7ff;
        }
      }

      .el-pager {
        li {
          background-color: #f5f7fa;
          border-radius: 4px;
          margin: 0 3px;
          color: #606266;
          font-weight: 500;
          min-width: 32px;
          transition: all 0.2s ease;

          &:hover {
            color: #1890ff;
            background-color: #e6f7ff;
          }

          &.is-active {
            background-color: #1890ff;
            color: #fff;
            font-weight: 600;
            box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);

            &:hover {
              background-color: #40a9ff;
            }
          }
        }
      }

      .el-pagination__jump {
        margin-left: 16px;
        color: #606266;

        .el-input__wrapper {
          background-color: #f5f7fa;
          border-radius: 4px;
        }
      }
    }
  }

  :deep(.employee-dialog) {
    border-radius: 12px;
    overflow: hidden;
    z-index: 2001 !important;

    .el-dialog__header {
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;
      margin: 0;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 16px 20px;
      border-top: 1px solid #f0f0f0;
    }

    .el-form-item__label {
      font-weight: 600;
      color: #606266;
    }

    .form-input,
    .form-select {
      width: 100%;

      .el-input__wrapper {
        border-radius: 8px;
        box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;

        &:hover,
        &.is-focus {
          box-shadow: 0 0 0 1px #1890ff inset;
        }
      }
    }

    .gender-group {
      .el-radio {
        margin-right: 20px;
        padding: 6px 10px;
        border-radius: 6px;
        transition: all 0.3s;

        &.is-checked {
          background-color: #e6f7ff;
        }

        &:hover {
          background-color: #f0f7ff;
        }

        .el-radio__input.is-checked .el-radio__inner {
          background-color: #1890ff;
          border-color: #1890ff;
        }

        .el-radio__input.is-checked + .el-radio__label {
          color: #1890ff;
          font-weight: 500;
        }
      }
    }

    .dialog-footer {
      .el-button {
        border-radius: 8px;
        padding: 8px 20px;
        font-weight: 500;
        transition: all 0.3s;

        .el-icon {
          margin-right: 4px;
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }

      .submit-btn {
        background: linear-gradient(135deg, #1890ff, #36a6ff);
        border-color: #1890ff;

        &:hover {
          background: linear-gradient(135deg, #40a9ff, #5cbbff);
          border-color: #40a9ff;
        }
      }
    }
  }
}
</style>
